package com.ax.associator.system.service.Impl;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.ax.associator.shopassistant.dao.SysUserMapper;
import com.ax.associator.store.common.utils.MD5Utils;
import com.ax.associator.system.dao.LoginMapper;
import com.ax.associator.system.service.LoginService;
import com.ax.base.system.domain.SysUserDO;
import com.google.gson.Gson;
@Service
public class LoginServiceImpl implements LoginService {

	@Autowired
	LoginMapper loginMapper;
	
	@Autowired
	SysUserMapper sysUserMapper;
	
	@Autowired
	RedisTemplate<String, String> redisTemplate;

	/**
     * 登录(药师,医师)
     * 
     * @param passWord,userName
     * 
     * @return SUCC
     */
	@Override
	public SysUserDO queryUserLoginSer(String userName, String passWord) {
		passWord = MD5Utils.encrypt(userName, passWord);
		String key = userName + passWord;
		SysUserDO sysUser = sysUserMapper.querySysUserDO(passWord, userName);
		if (sysUser == null){
			return null;
		}
		String userTypeCode = sysUser.getUserTypeCode();
		SysUserDO users = getUserByKey(key);
        if (users != null) {
    	sysUser = users;
        return sysUser;
        }
        if (userTypeCode.equals("01")) { //医师
        	sysUser = this.sysUserMapper.queryDoctorInfo(userName,passWord);
        }
        if (userTypeCode.equals("02")) { //药师
        	sysUser = this.sysUserMapper.queryPharmacistInfo(userName, passWord);
        }
        if (userTypeCode.equals("03")) { //药店人员
        	sysUser = this.sysUserMapper.queryStoreInfo(userName, passWord);
        }else{
        	//药监局
    //    	sysUser = this.sysUserMapper.querySpdaInfo(loginName, loginPwd);
        }
        if (sysUser.getUsername() != null && !"".equals(sysUser.getUsername())) {
        	addUser(key,3600L,sysUser);
        }
		return sysUser;
	}
	//保存用户
	private void addUser(String key,Long time,SysUserDO sysUserDO){
		Gson gson = new Gson();
		redisTemplate.opsForValue().set(key, gson.toJson(sysUserDO),time,TimeUnit.MINUTES);
	}
	//获取用户
	private SysUserDO getUserByKey(String key){
		Gson gson = new Gson();
		SysUserDO user = null;
		String userJson = redisTemplate.opsForValue().get(key);
		if(StringUtils.isNotEmpty(userJson)){
			user =  gson.fromJson(userJson, SysUserDO.class);
		}
		return user;
	}
}
